package com.tl.satoken.task;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tl.satoken.service.GameRoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class GameMatchCountdownTask {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private GameRoomService gameRoomService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Scheduled(fixedRate = 1000)
    public void checkCountdownExpired() {
        try {
            String pattern = "minigame:player:*:countdown";
            Set<String> countdownKeys = redisTemplate.keys(pattern);

            if (countdownKeys == null || countdownKeys.isEmpty()) {
                return;
            }

            long currentTime = System.currentTimeMillis();

            for (String countdownKey : countdownKeys) {
                try {
                    Object countdownData = redisTemplate.opsForValue().get(countdownKey);
                    if (countdownData == null) {
                        continue;
                    }

                    Map<String, Object> countdownMap = (Map<String, Object>) countdownData;
                    Long expireTime = (Long) countdownMap.get("expireTime");
                    String roomId = (String) countdownMap.get("roomId");
                    Integer gameId = (Integer) countdownMap.get("gameId");

                    if (expireTime != null && currentTime >= expireTime) {
                        log.info("玩家倒计时到期，房间ID: {}, 游戏ID: {}", roomId, gameId);
                        
                        gameRoomService.startGameByCountdown(roomId, gameId);
                        
                        redisTemplate.delete(countdownKey);
                        log.info("已清除倒计时记录: {}", countdownKey);
                    }
                } catch (Exception e) {
                    log.error("处理倒计时记录失败: {}", countdownKey, e);
                }
            }
        } catch (Exception e) {
            log.error("检查倒计时到期失败", e);
        }
    }
}
